﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BLL;
using IFactory;

public partial class UserLogin : System.Web.UI.Page
{
    IAuthentication dllAuthentication = new Authentication();
    public string companyName = System.Configuration.ConfigurationManager.AppSettings["CompanyName"].ToString();

    protected void Page_Load(object sender, EventArgs e)
    {
        
        System.Web.HttpContext.Current.Session["UserName"] = null;
        Page.RegisterStartupScript("getheighandwidth", "<script>document.getElementById('h1h').value=window.screen.availHeight;document.getElementById('h2w').value= window.screen.width ;</script>");
        if (ValidateIp())
        {
            //Response.Write("正确进入OA自动登录流程" + Request.UserHostAddress);
            //如果有OA传入的链接则自动登录。
            OALogin();
        }
        else
        {
            //Response.Write("不正确" + Request.UserHostAddress);
        }

    }

    /// <summary>
    /// 判断来源IP
    /// </summary>
    bool ValidateIp()
    {
        string Ip = Request.UserHostAddress;
        if (Ip != null && Ip != string.Empty)
        {
            //判断是否为非IpV4地址
            if (Ip.IndexOf(".") == -1)
            {
                return false;
            }
            if (Ip.Substring(0, 9) == "192.168.2" || Ip.Substring(0, 9) == "192.168.3" || Ip.Substring(0, 9) == "192.168.4" || Ip.Substring(0, 7) == "127.0.0")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }


    /// <summary>
    /// 用于OA整合单点登录
    /// </summary>
    /// <remarks>
    /// 用于OA界面链接到计划系统的自动登录，
    /// 判断Url传参的ItCode和密码，
    /// 密码为密文形式传递，本地解密并在次加密为计划系统的密码算法MD5。
    /// 符合即完成登录操作并登入界面
    /// </remarks>
    void OALogin()
    {
        ////int _height = Convert.ToInt32(this.h1h.Value);
        ////string _width = this.h2w.Value;
        //判断OA中Url链接是否包含Openpage参数。
        //if (Request.QueryString["loginPage"] != null)
        if(Request.Form["Username"]!=null)
        {
            Response.Write("正确获取用户名post值" + Request.Form["Username"].ToString());
            //解密参数字符串,目标字符串格式为(暂时不加解密)
            //Username=itcode&Password=旧密码&newPassword=新密码&sType=1&loginTime=当前时间（小时：分钟：秒）
            //string parameter = Request.QueryString["loginPage"].ToString();
            //string[] parameters = parameter.Split('&');
            //if (parameters.Length == 7)
            {
                //int _height = Convert.ToInt32(parameters[5].Substring(parameters[5].IndexOf("=")));
                //int _height = Convert.ToInt32(Request.QueryString["sheight"]);
                int _height = Convert.ToInt32(Request.Form["sheight"]);
                //string _width = parameters[6].Substring(parameters[6].IndexOf("="));
                //string _width = Request.QueryString["swidth"].ToString();
                string _width = Request.Form["swidth"].ToString();
                Session["_width"] = _width;
                //当前时间的转化秒值，例如2010-10-27 13:48:04当前时间转化为：49210
                //int loginTime = Convert.ToInt32(parameters[4].Substring(parameters[4].IndexOf("=")));
                //int loginTime = Convert.ToInt32(Request.QueryString["loginTime"]);
                int loginTime = Convert.ToInt32(Request.Form["loginTime"]);
                //构建本地时间转化秒值，用于对比
                DateTime localdate = DateTime.Now;
                int hour = (localdate.Hour * 3600);
                int mm = (localdate.Minute * 60);
                //拼成目标时间值，并转为double型，用于比对。
                int localtime = hour + mm + localdate.Second;
                //string sType = parameters[3].Substring(parameters[3].IndexOf("="));
                //string sType = Request.QueryString["sType"].ToString();
                //判断类型， 类型为0表示登录。判断当前时间是否超时，正负误差3分钟。
                if ((loginTime - localtime >= -180 || loginTime - localtime <= 180))
                {
                    //string username = parameters[1].Substring(parameters[1].IndexOf("="));
                    string username = Request.Form["Username"].ToString();
                    //string userpassword = parameters[2].Substring(parameters[2].IndexOf("="));
                    string userpassword = Request.Form["Password"].ToString();
                    SqlParameter[] sqlparam = new SqlParameter[1];
                    sqlparam[0] = new SqlParameter("@ItCode", username);
                    //sqlparam[1] = new SqlParameter("@UserPassWord", userpassword);
                    string sql = "select * from DS_UserInfo where ItCode = @ItCode and IsDimission=0  ";
                    DataTable dt = DAL.SqlHelper.ExecuteDataset(DAL.SqlHelper.connStr, CommandType.Text, sql, sqlparam).Tables[0];
                    if (dt.Rows.Count > 0)
                    {

                        Response.Write("正确登录" + Request.Form["Username"].ToString());
                        Model.UserInfo objUserInfo = new Model.UserInfo();
                        //写入Session
                        objUserInfo.UserName = dt.Rows[0]["UserName"].ToString();
                        if (objUserInfo.UserName == "system")
                        {
                            string _url = "Admin/Main.aspx";
                            string a = DateTime.Now.Ticks.ToString();
                            //Page.RegisterStartupScript("windowsopen", "<script language=javascript>window.open('" + _url + "'," + a + ",'height= " + _height + ",width=" + _width + ",top=0,left=0,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no');window.opener=null;self.close();</script>");
                            Response.Redirect(_url);
                        }
                        else
                        {
                            string _url = "Main.aspx";
                            string a = DateTime.Now.Ticks.ToString();
                            //Page.RegisterStartupScript("windowsopen", "<script language=javascript>window.open('" + _url + "'," + a + ",'height= " + _height + ",width=" + _width + ",top=0,left=0,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no');window.opener=null;self.close();</script>");
                            Response.Redirect(_url);
                        }
                    }
                    else
                    {
                        Utility.HttpHelp.alert("用户名或密码不正确", Page);
                        this.txtPassWord.Text = "";
                        this.txtUserName.Text = "";
                        //Response.Redirect("UserLogin.aspx");
                    }
                }
                else
                {
                    Response.Write("登陆时间与服务器时间有误");
                    Utility.HttpHelp.alert("登陆时间与服务器时间有误！", Page);
                }
            }


        }
        else
        {
            //Utility.HttpHelp.alert("aa", Page);
        }
        //TODO:捕捉Url参数并解密密码
        //TODO:模拟本地登录写入Session。
        //TODO:跳转至欢迎页。
    }

    /// <summary>
    /// 登录事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ibtnLogin_Click(object sender, ImageClickEventArgs e)
    {
        int _height = Convert.ToInt32(this.h1h.Value);
        string _width = this.h2w.Value;
        Session["_width"] = _width;
        if (this.txtUserName.Text.Length == 0)
        {
            Utility.HttpHelp.alert("请输入用户名", Page);
            return;
        }
        if (this.txtPassWord.Text.Length == 0)
        {
            Utility.HttpHelp.alert("请输入密码", Page);
            return;
        }
        if (this.txtUserName.Text != "system")
        {
            int result = dllAuthentication.UserLogin(this.txtUserName.Text.Trim(), this.txtPassWord.Text.Trim());
            if (result > 0)
            {
                string _url = "Main.aspx";
                string a = DateTime.Now.Ticks.ToString();
                //Page.RegisterStartupScript("windows", "<script>alert('" + _url + "','" + a + "','height=715,width=1020,top=0,left=0,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no')</script>");
                
                // Response.Write("<script>window.open('Main.aspx','','fullscreen=1,menubar=0,toolbar=0,directories=0,location=0,status=0,scrollbars=0');self.close();</script>");  
                //Response.Write("<script>window.open('Main.aspx','','fullscreen=1')'window.opener=null;self.close();</script>");
                //Utility.HttpHelp.ShowModalDialogWindow("Main.aspx", 1024, 748, 0, 0,Page);
                //Response.Write("<script>window.open('Main.aspx','',' fullscreen=1 0, 0,Page'); window.opener=null;self.close();</script>");
                //Response.Redirect("Main.aspx");
                // Response.Write("<script language=javascript> newwin=window.open('Main.aspx','','scrollbars'); if (document.all){newwin.moveTo(0,0)newwin.resizeTo(screen.availWidth,screen.availHeight)}newwin.location='Main.aspx'  </script>");
                //登陆弹出窗体
                //Page.RegisterStartupScript("windowsopen", "<script language=javascript>window.open('" + _url + "'," + a + ",'height= " + _height + ",width=" + _width + ",top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=yes');window.opener=null;self.close();</script>");
                Response.Redirect(_url);
            }
            else
            {
                Utility.HttpHelp.alert("用户名或密码不正确", Page);
                this.txtPassWord.Text = "";
                this.txtUserName.Text = "";
                //Response.Redirect("UserLogin.aspx");
            }
        }
        else
        {
            int result = dllAuthentication.UserLogin(this.txtUserName.Text.Trim(), this.txtPassWord.Text.Trim());
            if (result > 0)
            {
                this.txtUserName.Text = "";
                string _url = "Admin/Main.aspx";
                string a = DateTime.Now.Ticks.ToString();
                Page.RegisterStartupScript("windowsopen", "<script language=javascript>window.open('" + _url + "'," + a + ",'height= " + _height + ",width=" + _width + ",top=0,left=0,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no');window.opener=null;self.close();</script>");
            }
            else
            {
                Utility.HttpHelp.alert("用户名或密码不正确", Page);
                this.txtPassWord.Text = "";
                this.txtUserName.Text = "";
                //Response.Redirect("UserLogin.aspx");
            }
        }
    }
}
